<?php
namespace app\api\validate;

use think\Db;
use think\Validate;

/**
 * Class MovecarValidate
 * @package app\api\validate
 * @author zhenHong~
 */
class MovecarValidate extends Validate{
    protected $rule = [
        'a_id' => ['require','regex' => '/^[+]{0,1}(\d+)$/'],
        'page' => ['number','require'],
        'num'  => ['number','require'],
        'buff' => ['in'=>'1,2'],
        'code' => ['require','checkMyCode'],
        'phone' => ['require','regex'=>'0?(13|14|15|17|18|19)[0-9]{9}'],
        'car_num' => ['require','checkCarNumber'],
        'id' => ['require','regex' => '/^[+]{0,1}(\d+)$/']
    ];

    protected $message = [
        'a_id' => '商户参数错误',
        'page' => '分页参数错误',
        'num'  => 'num数错误',
        'buff' => '状态参数错误',
        'code.require' => '二维码参数错误',
        'code.checkMyCode' => '二维码不可用',
        'phone' => '手机号格式错误',
        'car_num' => '车牌号错误',
        'id' => '二维码id错误'
    ];

    protected $scene = [
        // 用户绑定手机号
        'bindUser'      => ['code'=>['require'],'phone','car_num'],
        // 批量生成二维码
        'createQrcodes' => ['a_id','num'],
        // 禁用挪车二维码
        'editMove'      => ['id','buff'],
        // 二维码列表
        'qrcodeList'    => ['a_id','page','num']
    ];

    /**
     * @param $value
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 检查二维码    是否存在且可用
     */
    protected function checkMyCode($value){
        $result = Db::name('Move')
            ->where(['code' => $value])
            ->field('car_num,id,buff')
            ->find();
        if($result['car_num'] && $result['buff'] == 1){
            return true;
        }else{
            return false;
        }
    }

    /**
     * @param $value
     * @return bool
     * 检查车牌号
     */
    protected function checkCarNumber($value){
        $chinese = mb_substr($value, 0, 1);
        $is['chinese'] = preg_match('/[\x{4e00}-\x{9fa5}]+/u', $chinese);
        $az = mb_substr($value, 1, 1);
        $is['az'] = preg_match('/[a-zA-Z]{1}/', $az);
        $z5 = mb_substr($value, 2, 5);
        $is['z5'] = preg_match('/[0-9a-zA-Z]{5}/', $z5);
        if ($is['chinese'] && $is['az'] && $is['z5']) {
            return true;
        }else{
            return false;
        }
    }

}